package com.googlecode.latvian_ebooks.glossary

import java.io.File
import scala.io.Source

object FileSearchUtility {

  val fragmentsFile: String = "data/words.txt"
  val fragments: List[(Int, String)] = read(fragmentsFile)

  /**
   * Read list "fragments" - each item is one paragraph from Monadologie
   */
  def read(fileName: String): List[(Int, String)] = {
    val lines: List[String] = Source.fromFile(new File(fileName)).getLines.toList
    val num: Iterator[Int] = (1 to lines.length).iterator
    lines.map { line => (num.next, line) }
  }

  def findOccurences(term: String): List[Int] = {
    val lcTerm = term.toLowerCase
    for (fragment <- fragments if contains(fragment._2, lcTerm)) yield fragment._1
  }

  def contains(fragment: String, term: String): Boolean = {
    val lcFragment: String = fragment.toLowerCase();
    if (term.length() < 3) {
      System.err.println("Very short term '" + term + "'");
      System.exit(0);
    }
    val simpleMatch = lcFragment.indexOf(term.substring(0, term
      .length() - 2)) > -1;
    if (simpleMatch)
      return true;
    val latinFragment: String = latinize(lcFragment)
    val latinTerm: String = latinize(term)
    val advancedMatch: Boolean = latinFragment.indexOf(latinTerm.substring(0,
      latinTerm.length() - 2)) > -1;

    if (!advancedMatch)
      return false;
    System.out.println("!!! Suspect ortography for term '" + term + "'");
    return true;
  }

  def getLocationFragments(locationList: List[Location]): List[Int] = {
    locationList.map(loc => loc.getFragmentNum)
  }

  /**
   * Replace French letters with diacritics with regular latin leters
   * 
   * @param arg
   *            the string to replace
   * @return latinized string
   */
  def latinize(arg: String): String = {
    val arg1 = arg.replaceAll("\u00E9", "e"); // e with 'accent ague'
    val arg2 = arg1.replaceAll("\u00E0", "a"); // a with 'accent grave'
    val arg3 = arg2.replaceAll("\u00E8", "e"); // e with 'accent grave'
    val arg4 = arg3.replaceAll("\u00F9", "u"); // u with 'accent grave'
    val arg5 = arg4.replaceAll("\u00E2", "a"); // a with 'circumflex'
    val arg6 = arg5.replaceAll("\u00EA", "e");
    val arg7 = arg6.replaceAll("\u00EE", "i");
    val arg8 = arg7.replaceAll("\u00F4", "o");
    val arg9 = arg8.replaceAll("\u00FB", "u");
    val result = arg9.replaceAll("\u00E7", "c");
    return result
  }

}